package com.zhou.framework.pool;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.concurrent.BasicThreadFactory;

import java.util.concurrent.*;

@Slf4j
public class DefaultThreadPool extends ScheduledThreadPoolExecutor {

    @Getter
    @Setter
    private ThreadTrigger trigger = null;

    @Getter
    @Setter
    private boolean debug = false;

    public DefaultThreadPool(int corePoolSize, int maximumPoolSize) {
        super(corePoolSize,new BasicThreadFactory.Builder().namingPattern("schedule-pool-%d").daemon(true).build(),
                new ThreadPoolExecutor.CallerRunsPolicy());
        setMaximumPoolSize(maximumPoolSize);
    }

    @Override
    protected void beforeExecute(Thread t, Runnable r) {
        if(trigger != null && debug){
            try{
                trigger.beforeExecute(t,r);
            }catch (Throwable e){
                log.error("[beforeExecute]trigger failed.",e);
            }

        }
    }

    @Override
    protected void afterExecute(Runnable r, Throwable t) {
        if(trigger != null){
            try{
                trigger.afterExecute(r,t);
            }catch (Throwable e){
                log.error("[afterExecute]trigger failed.",e);
            }
        }
    }

    /**
     * 关闭线程池前执行
     */
    @Override
    protected void terminated() {
        if(trigger != null){
            try{
                trigger.beforeShutdown();
            }catch (Throwable e){
                log.error("[terminated]trigger failed.",e);
            }
        }
    }


}
